﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DevExpress.Xpf.Grid;
using WT.Controls;
using System.ComponentModel;

namespace WT
{
	public partial class Navigate : UserControl
	{

        // http_://silverlighter.ru/blogs/silverlighter_blog/archive/2010/07/06/chto-takoe-datastore_3F00_.aspx
        // http_://stackoverflow.com/questions/2453779/handle-property-change-event-listeners-lots-of-them-more-elegantly-dictionary

        public event PropertyChangedEventHandler DataContextChanged;
        
        protected void OnDataContextChanged(string propertyName)
        {
            if (DataContextChanged != null)
            {
                DataContextChanged(this, new PropertyChangedEventArgs("DataContext"));
            }
        }

        bool isDragDropInEffect = false;
        Point pos;

        public Navigate()
		{
			// Required to initialize variables
			InitializeComponent();
            this.DataContext = "";
		}

        private void radDomainDataSource1_LoadedData(object sender, Telerik.Windows.Controls.DomainServices.LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Ошибка загрузки", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }

            gridControl1.Columns.Remove(gridControl1.Columns["ID_USER"]);
            //gridControl1.Columns.Remove(gridControl1.Columns["ID_NAVIGATE_WELL"]);
            gridControl1.Columns.Remove(gridControl1.Columns["ID_MEST"]);

            gridControl1.GroupBy("NAME_NGDU");
            gridControl1.GroupBy("NAME_NGP");
            //gridControl1.GroupBy("NAME_NPS");
            gridControl1.GroupBy("NAME_MEST");
            gridControl1.GroupBy("NAME_PAD");

            gridControl1.Columns["NAME_WELL_PAD"].VisibleIndex = 0;
            gridControl1.Columns["NAME_POOL"].VisibleIndex = 1;
            

            gridControl1.Columns["NAME_NGDU"].Header = "НГДУ";
            gridControl1.Columns["NAME_NGP"].Header = "НГП";
            gridControl1.Columns["NAME_NPS"].Header = "НПС";
            gridControl1.Columns["NAME_MEST"].Header = "Месторождение";
            gridControl1.Columns["NAME_PAD"].Header = "Куст";
            gridControl1.Columns["NAME_MEST"].Header = "М/Р";
            gridControl1.Columns["NAME_WELL_PAD"].Header = "Скв/Куст";
            gridControl1.Columns["NAME_POOL"].Header = "Пласт";

            gridControl1.Columns["ID_WELL"].Visible = false;
            gridControl1.Columns["NAME_METHOD"].Visible = false;
            gridControl1.Columns["NAME_WELL"].Visible = false;
            gridControl1.Columns["NAME_MODE"].Visible = false;
            gridControl1.Columns["NAME_FUNC"].Visible = false;
            gridControl1.Columns["DATE_MODE"].Visible = false;

            gridControl1.Columns["ID_WELL"].Header = "Код скважины";
            gridControl1.Columns["NAME_METHOD"].Header = "Способ";
            gridControl1.Columns["NAME_WELL"].Header = "Скважина";
            gridControl1.Columns["NAME_MODE"].Header = "Состояние";
            gridControl1.Columns["NAME_FUNC"].Header = "Назначение";
            gridControl1.Columns["DATE_MODE"].Header = "Дата состояния";

        }

        /*=================================gridControl1==========================*/
        private void gridControl1_FilterChanged(object sender, DevExpress.Xpf.Core.WPFCompatibility.SLRoutedEventArgs e)
        {
            gridControl1.ExpandAllGroups();
        }

        private void TableView_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter | e.Key == System.Windows.Input.Key.Escape)
            {
                tableView1.SelectRow(0);
                
                //gridControl1.View.SelectRow(0);
                // FocusedRowHandle = 0;
                //gridControl1.View.filter
            }
        }

        // Определение типа строки
        private string GetRowType(int rowHandle)
        {
            if (gridControl1.IsGroupRowHandle(rowHandle)) return "Group Row";
            if (rowHandle == GridControl.AutoFilterRowHandle) return "Automatic Filter Row";
            if (rowHandle == GridControl.NewItemRowHandle) return "New Item Row";
            if (rowHandle == GridControl.InvalidRowHandle) return "Invalid Row";
            return "Data Row";
        }

        private void tableView1_SelectionChanged(object sender, DevExpress.Xpf.Grid.GridSelectionChangedEventArgs e)
        {
            //if (gridControl1 != null && gridControl1.View.GetSelectedRowHandles().Length != 0)
            //if (gridControl1 != null && ((GridViewBase)gridControl1.View).GetSelectedRowHandles().Length != 0)
            if (gridControl1 != null && tableView1.SelectedRows.Count != 0)
            {
                int rowHandle = tableView1.GetSelectedRowHandles()[0];
                if (gridControl1.IsGroupRowHandle(rowHandle)) gridControl1.ExpandGroupRow(rowHandle);
                if (GetRowType(rowHandle) == "Data Row")
                {
                    //string id_well = gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"]).ToString();
                    //string id_well = ((decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"])).ToString();
                    //decimal id_well = (decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"]);

                    this.DataContext = ((decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"])).ToString();
                    OnDataContextChanged("DataContext");
                    //Current_id_well = ((decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"])).ToString();
                    //_current_id_well = ((decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"])).ToString();

                    //current_id_well.Value = ((decimal)gridControl1.GetCellValue(rowHandle, gridControl1.Columns["ID_WELL"])).ToString();

                    //MessageBox.Show(id_well.ToString(), "Ошибка!", MessageBoxButton.OK);
                    //Load_wtd_well_tab(id_well);
                }
            }
        }

        /*=================================gridControl1==========================*/


        /*=================================LoadFromService=======================*
        private void Load_wtd_navigate()
        {
            gridControl1.ShowLoadingPanel = true;
            wTDNAVIGATEDomainDataSource.Load();
        }

        private void wTDNAVIGATEDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            gridControl1.ShowLoadingPanel = false;
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
                return;
            }

            gridControl1.GroupBy("НГДУ");
            gridControl1.GroupBy("НГП");
            //gridControl1.GroupBy("НПСООРУЖЕНИЯ");
            gridControl1.GroupBy("МЕСТОРОЖДЕНИЕ");
            //gridControl1.GroupBy("КУСТ");

            gridControl1.Columns["МЕСТОРОЖДЕНИЕ"].Header = "М/Р";

            gridControl1.Columns["NUM"].Visible = false;
            gridControl1.Columns["СКВАЖID"].Visible = false;
            gridControl1.Columns["МРКОДМР"].Visible = false;
            gridControl1.Columns["СПОСОБЭКСПЛ"].Visible = false;
            gridControl1.Columns["СКВАЖИНА"].Visible = false;
            gridControl1.Columns["СОСТОЯНИЕ"].Visible = false;
            gridControl1.Columns["НАЗНАЧЕНИЕ"].Visible = false;
        }

        */
		
		/*
        public void Load_wtd_well_tab(decimal id_well)
        {
            try
            {
                /*
                if (((this.Parent as Border).Parent as Grid)is MainPage)
                {
                    MessageBox.Show("is MainPage", "!", MessageBoxButton.OK);
                }*/

                    /*
                if (ContentFrame.Content is Home)
                {
                    (ContentFrame.Content as Home).id_wellTextBox.Text = id_well.ToString();
                    (ContentFrame.Content as Home).ReloadData();
                }
                if (ContentFrame.Content is About)
                {
                    (ContentFrame.Content as About).id_wellTextBox.Text = id_well.ToString();
                    (ContentFrame.Content as About).ReloadData();
                }
                if (ContentFrame.Content is HomeV)
                {
                    (ContentFrame.Content as HomeV).id_wellTextBox.Text = id_well.ToString();
                    (ContentFrame.Content as HomeV).ReloadData();
                }
                if (ContentFrame.Content is HomeG)
                {
                    (ContentFrame.Content as HomeG).id_wellTextBox.Text = id_well.ToString();
                    (ContentFrame.Content as HomeG).ReloadData();
                }
                if (ContentFrame.Content is Page1)
                {
                    (ContentFrame.Content as Page1).id_wellTextBox.Text = id_well.ToString();
                    (ContentFrame.Content as Page1).ReloadData();
                }*/
           /* }
            catch (System.Exception se)
            {
                MessageBox.Show(se.Message, "Ошибка!", MessageBoxButton.OK);
            }
        }*/

        private void wTDV_NAVIGATE_WELLDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void UserControl_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            //FrameworkElement fEle = sender as FrameworkElement;
            FrameworkElement fEle = (this as FrameworkElement).Parent as FrameworkElement;
            isDragDropInEffect = true;
            // x and y coords of mouse pointer position
            pos = e.GetPosition(null);
            // Enable mouse capture on element
            fEle.CaptureMouse();
            // Set the cursor to 'Hand' when mouse pointer is over element
            fEle.Cursor = Cursors.Hand;
        }

        private void UserControl_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.MessageBox.Show("Grid", "Load Error", System.Windows.MessageBoxButton.OK);
            /*if (isDragDropInEffect)
            {
                //FrameworkElement ele = sender as FrameworkElement;
                FrameworkElement ele = (this as FrameworkElement).Parent as FrameworkElement;
                isDragDropInEffect = false;
                // Removes Mouse Capture from Element being dragged
                ele.ReleaseMouseCapture();
            }*/
        }

        private void UserControl_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragDropInEffect)
            {
                //FrameworkElement currEle = sender as FrameworkElement;
                FrameworkElement currEle = (this as FrameworkElement).Parent as FrameworkElement;

                // Retrieving the item's current x and y position
                double xPos = e.GetPosition(null).X - pos.X;
                double yPos = e.GetPosition(null).Y - pos.Y;

                // Re-position Element
                //currEle.SetValue(Canvas.TopProperty, yPos + (double)currEle.GetValue(Canvas.TopProperty));
                //currEle.SetValue(Canvas.LeftProperty, xPos + (double)currEle.GetValue(Canvas.LeftProperty));

                currEle.SetValue(Canvas.TopProperty, yPos + (double)currEle.GetValue(Canvas.TopProperty));
                currEle.SetValue(Canvas.LeftProperty, xPos + (double)currEle.GetValue(Canvas.LeftProperty));

                // Reset the new position value
                pos = e.GetPosition(null);
            }
        }

        private void NavGridShadow_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			BringToFront(NavGridShadow);
			e.Handled = true;
        }

        private void NavGridShadow_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            BringToFront(busyIndicator);
        }

        private void BringToFront(object sender)
        {
            Panel parent = (Panel)((FrameworkElement)sender).Parent;

            int z = getHighestValue(parent);

            for (int i = 0; i < parent.Children.Count; i++)
            {
                if (sender.Equals(parent.Children[i]))
                {
                    parent.Children[i].SetValue(Canvas.ZIndexProperty, z);
                }
            }
        }
        
		private int getHighestValue(Panel parent)
        {
            int highest = 0;
            foreach (var child in parent.Children)
            {
                var val = (int)child.GetValue(Canvas.ZIndexProperty);
                if (val > highest) {
                    highest = val;
                }
                child.SetValue(Canvas.ZIndexProperty, val - 1);
            }
            return highest;
        }

		private void tableView1_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
		}

        /*=================================LoadFromService=======================*/
    }

}